import React, { memo, useEffect, useRef, useState } from "react";
import { fetchTable } from "@common/envOverviewApi/search";
import { Button, Icon, Input, Select, Table, Tooltip } from "antd";
import useFormatMessage from "@pkgs/hooks/useFormatMessage";
import Highlighter from "react-highlight-words";
import { envStatus } from "../utils";
import Details from "./Details";
import _ from "lodash";

import { EnvImpListDataType } from "@interface";
import type { PaginationConfig } from "antd/es/table";

type DataIndex = keyof EnvImpListDataType;

type Props = {
  keywords: string;
};

interface FilterType {
  "_source.personalstatus"?: string[];
  "_source.generalstatus"?: string[];
  "_source.servicestatus"?: string[];
  "_source.machinestatus"?: string[];
}

/**
 * @func 表格组件
 * @param props
 * @returns React.FC
 */
const Detection: React.FC<Props> = (props) => {
  const { Option } = Select;
  const { keywords } = props;
  const [dataSource, setDataSource] = useState([]);
  //NINT 接口暂时写死了第一页，5000 条查询，以进行前端搜索和分页，这两个声明暂且留下，后续若是用了后端搜索可扩展
  // const [current, setCurrent] = useState<number | undefined>(1);
  // const [pageSize, setPageSize] = useState<number | undefined>(10);
  const [loading, setLoading] = useState<boolean>(false);
  const searchInput = useRef<Input>(null);
  const [searchText, setSearchText] = useState("");
  const [searchedColumn, setSearchedColumn] = useState("");
  const [filterData, setFilterData] = useState<FilterType>({});

  const intlFormatMsg = useFormatMessage();

  const handleChange = (value: any) => {
    console.log(`selected ${value}`);
  };

  useEffect(() => {
    if (keywords) {
      getTableData(keywords);
    }
  }, []);

  //NOTE 节点更新请求新节点数据
  useEffect(() => {
    if (keywords) {
      getTableData(keywords);
    }
  }, [keywords]);

  const getTableData = (
    keywords: string,
    pageSize?: number | undefined,
    current?: number | undefined
  ) => {
    setLoading(true);
    fetchTable(keywords, pageSize, current).then((data) => {
      const { hits } = data.hits;
      setDataSource(hits);
      setLoading(false);
    });
  };

  //NOTE 当前页数、单页展示大小、页码跳转回调函数
  const pageChange = (
    pagination: PaginationConfig,
    filters: Partial<Record<string | number | symbol, string[]>>
  ) => {
    let data = {
      ...filters,
      ...filterData,
    };
    setFilterData(data);
    //NINT 接口暂时写死了第一页，5000 条查询，以进行前端搜索和分页，这两个声明暂且留下，后续若是用了后端搜索可扩展
    // const { current, pageSize } = pagination;
    // setCurrent(current);
    // setPageSize(pageSize);
  };

  const handleSearch = (
    selectedKeys: string[],
    confirm: () => void,
    dataIndex: DataIndex
  ) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters: () => void) => {
    clearFilters();
    setSearchText("");
  };

  const getColumnSearchProps = (dataIndex: any) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }: any) => (
      <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() =>
            handleSearch(selectedKeys as string[], confirm, dataIndex)
          }
          style={{ marginBottom: 8, display: "block" }}
        />
        <Button
          type="primary"
          onClick={() =>
            handleSearch(selectedKeys as string[], confirm, dataIndex)
          }
          icon="search"
          size="small"
          style={{ width: 90 }}
        >
          搜索
        </Button>
        <Button
          onClick={() => clearFilters && handleReset(clearFilters)}
          size="small"
          style={{ width: 90 }}
        >
          重置
        </Button>
        {/* //NINT 筛选和一键关闭，暂时没有作用，注释掉  */}
        {/* <Button
          type="link"
          size="small"
          onClick={() => {
            confirm({ closeDropdown: false });
            setSearchText((selectedKeys as string[])[0]);
            setSearchedColumn(dataIndex);
          }}
        >
          Filter
        </Button>
        <Button
          type="link"
          size="small"
          onClick={() => {
            close();
          }}
        >
          close
        </Button> */}
      </div>
    ),
    filterIcon: (filtered: boolean) => (
      //NINT ANTD3 版本Icon ts 类型错误，无影响，React.SFC 已于 16.7 弃用，如不想看到报错可修改 ANTD Icon 中 SFC为 FC
      <Icon type="search" style={{ color: filtered ? "#1890ff" : undefined }} />
    ),
    onFilter: (value: string, record: DataIndex) => {
      const data = dataIndex.split(".");
      if (data.length == 2) {
        return record[data[0]][data[1]]
          .toString()
          .toLowerCase()
          .includes((value as string).toLowerCase());
      } else if (data.length == 3) {
        return record[data[0]][data[1]][data[2]]
          .toString()
          .toLowerCase()
          .includes((value as string).toLowerCase());
      }
    },
    onFilterDropdownOpenChange: (visible: any) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
    render: (text: { toString: () => any }) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ""}
        />
      ) : (
        text
      ),
  });

  const columns = [
    {
      title: (
        <Tooltip
          placement="topLeft"
          title={
            <span>{intlFormatMsg({ id: "env.improved.prompt.hostname" })}</span>
          }
        >
          {intlFormatMsg({ id: "env.improved.hostname" })}&nbsp;
          <Icon
            type="exclamation-circle"
            style={{
              fontSize: "8px",
              position: "absolute",
            }}
          />
        </Tooltip>
      ),
      dataIndex: "_source.hostname",
      width: 150,
      ...getColumnSearchProps("_source.hostname"),
      render: (text: string) => {
        return <Details text={text} />;
      },
    },
    {
      title: (
        <Tooltip
          placement="topLeft"
          title={
            <span>{intlFormatMsg({ id: "env.improved.prompt.cpu" })}</span>
          }
        >
          {intlFormatMsg({ id: "env.improved.cpu" })}
        </Tooltip>
      ),
      dataIndex: "_source.util.cpu",
      width: 80,
      ...getColumnSearchProps("_source.util.cpu"),
    },
    {
      title: (
        <Tooltip
          placement="topLeft"
          title={
            <span>{intlFormatMsg({ id: "env.improved.prompt.mem" })}</span>
          }
        >
          {intlFormatMsg({ id: "env.improved.mem" })}
        </Tooltip>
      ),
      dataIndex: "_source.util.mem",
      width: 80,
      ...getColumnSearchProps("_source.util.mem"),
    },
    {
      title: (
        <Tooltip
          placement="topLeft"
          title={
            <span>{intlFormatMsg({ id: "env.improved.prompt.disk" })}</span>
          }
        >
          {intlFormatMsg({ id: "env.improved.disk" })}
        </Tooltip>
      ),
      dataIndex: "_source.util.disk",
      width: 80,
      ...getColumnSearchProps("_source.util.disk"),
    },
    {
      title: (
        <Tooltip
          placement="topLeft"
          title={
            <span>
              {intlFormatMsg({ id: "env.improved.prompt.generalstatus" })}
            </span>
          }
        >
          {intlFormatMsg({ id: "env.improved.generalstatus" })}&nbsp;
          <Icon
            type="exclamation-circle"
            style={{
              fontSize: "8px",
              position: "absolute",
            }}
          />
        </Tooltip>
      ),
      dataIndex: "_source.generalstatus",
      width: 80,
      filters: [
        { text: "未采集", value: "0" },
        { text: "成功", value: "1" },
        { text: "失败", value: "2" },
      ],
      filteredValues: filterData["_source.generalstatus"] || null,
      onFilter: (value: string, record: any) => {
        return record._source.generalstatus.toString().includes(value);
      },
      render: (text: number) => {
        return _.toString(envStatus(text));
      },
    },
    {
      title: (
        <Tooltip
          placement="topLeft"
          title={
            <span>
              {intlFormatMsg({ id: "env.improved.prompt.personalstatus" })}
            </span>
          }
        >
          {intlFormatMsg({ id: "env.improved.personalstatus" })}&nbsp;
          <Icon
            type="exclamation-circle"
            style={{
              fontSize: "8px",
              position: "absolute",
            }}
          />
        </Tooltip>
      ),
      dataIndex: "_source.personalstatus",
      width: 80,
      filters: [
        { text: "未采集", value: "0" },
        { text: "成功", value: "1" },
        { text: "失败", value: "2" },
      ],
      filteredValues: filterData["_source.personalstatus"] || null,
      onFilter: (value: string, record: any) => {
        return record._source.personalstatus.toString().includes(value);
      },
      render: (text: number) => {
        return _.toString(envStatus(text));
      },
    },
    {
      title: (
        <Tooltip
          placement="topLeft"
          title={
            <span>{intlFormatMsg({ id: "env.improved.prompt.cronnum" })}</span>
          }
        >
          {intlFormatMsg({ id: "env.improved.cronnum" })}
        </Tooltip>
      ),
      dataIndex: "_source.cronnum",
      width: 80,
      ...getColumnSearchProps("_source.cronnum"),
    },
    {
      title: (
        <Tooltip
          placement="topLeft"
          title={
            <span>
              {intlFormatMsg({ id: "env.improved.prompt.servicestatus" })}
            </span>
          }
        >
          {intlFormatMsg({ id: "env.improved.servicestatus" })}&nbsp;
          <Icon
            type="exclamation-circle"
            style={{
              fontSize: "8px",
              position: "absolute",
            }}
          />
        </Tooltip>
      ),
      dataIndex: "_source.servicestatus",
      width: 80,
      filters: [
        { text: "未采集", value: "0" },
        { text: "成功", value: "1" },
        { text: "失败", value: "2" },
      ],
      filteredValues: filterData["_source.servicestatus"] || null,
      onFilter: (value: string, record: any) => {
        return record._source.servicestatus.toString().includes(value);
      },
      render: (text: number) => {
        return _.toString(envStatus(text));
      },
    },
    {
      title: (
        <Tooltip
          placement="topLeft"
          title={
            <span>
              {intlFormatMsg({ id: "env.improved.prompt.machinestatus" })}
            </span>
          }
        >
          {intlFormatMsg({ id: "env.improved.machinestatus" })}
        </Tooltip>
      ),
      dataIndex: "_source.machinestatus",
      width: 80,
      filters: [
        { text: "健康", value: "0" },
        { text: "异常", value: "1" },
      ],
      filteredValues: filterData["_source.machinestatus"] || null,
      onFilter: (value: string, record: any) => {
        return record._source.machinestatus.toString().includes(value);
      },
      render: (text: number) => {
        return _.toString(text ? "异常" : "健康");
      },
    },
  ];

  return (
    <div>
      {/* //TODO 模板及自定义筛选这块的逻辑还没设计好 */}
      {/* <Select
        defaultValue="initial"
        style={{ width: 120 }}
        onChange={handleChange}
      >
        <Option value="basics">基础环境</Option>
        <Option value="initial">初始化检测</Option>
        <Option value="custom">自定义检测</Option>
        <Option value="appmes">应用信息</Option>
        <Option value="timedtask">定时任务</Option>
      </Select>
      <Select
        defaultValue="custom2"
        style={{ width: 120 }}
        onChange={handleChange}
      >
        <Option value="custom1">自定义检测1</Option>
        <Option value="custom2">自定义检测2</Option>
      </Select> */}
      <Table
        style={{ marginTop: "15px" }}
        rowKey="_id"
        columns={columns as any}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ["5", "10", "20", "30", "40", "50", "100"],
          defaultPageSize: 5,
        }}
        dataSource={dataSource}
        loading={loading}
        onChange={pageChange}
      />
    </div>
  );
};

export default memo(Detection);
